#include "taskcreator.h"
#include "ui_taskcreator.h"

#include "QRandomGenerator"

#include "QMessageBox"

TaskCreator::TaskCreator(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TaskCreator)
{
    ui->setupUi(this);

    connect(&colorSelector, &QColorDialog::colorSelected, this, &TaskCreator::on_userSelectColor);
}

TaskCreator::~TaskCreator()
{ delete ui; }

void TaskCreator::setTaskCreation(bool status, const QVector<Group*> *groups){
    isTaskCreating = status;

    this->groups = groups;

    ui->nameLineEdit->clear();
    if(status){//добавление задания
        ui->colorGroup->hide();

        ui->groupCB->clear();//В списке могут быть удалённые задания
        for(auto &group : *groups)
            ui->groupCB->addItem(*group->name);

        ui->taskCount->show();
        ui->groupTimerGroup->show();
    }
    else{//добавленеи группы
        ui->colorGroup->show();

        ui->taskCount->hide();
        ui->groupTimerGroup->hide();
    }
    ui->nameLineEdit->setFocus();
}

void TaskCreator::on_addTaskBtn_clicked(){
    QString name = ui->nameLineEdit->text();
    if(name.length() == 0)
    {
        ui->nameLineEdit->setFocus();
        return;
    }

    if(isTaskCreating){
        int groupId = -1;
        for(auto &group : *groups){
            if(group->name == ui->groupCB->currentText()){
                groupId = group->id;
                break;
            }
        }
        int taskCount = ui->taskCount->value();
        int timer     = ui->timerEdit->value();

        emit sendTaskToParent(&name, groupId, timer, taskCount);

        ui->timerEdit->setValue(1);
        ui->taskCount->setValue(1);
        ui->groupCB->setCurrentIndex(0);
    }
    else{
        emit sendGroupToParent(&name, &groupColor);
    }

    ui->nameLineEdit->clear();

    hide();
}

void TaskCreator::on_exitTaskBtn_clicked()
{ hide(); }

void TaskCreator::on_changeColorBtn_clicked(){
    QColor randColor = QColor::fromRgb(QRandomGenerator::global()->generate());
    colorSelector.setCurrentColor(randColor);
    colorSelector.show();
}

void TaskCreator::on_userSelectColor(const QColor &color){
    QPalette pal = palette();

    pal.setColor(QPalette::Background, color);
    ui->colorWgt->setAutoFillBackground(true);
    ui->colorWgt->setPalette(pal);

    groupColor = color;
}
